import requests
import json
import execjs

headers = {
    'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.90 Safari/537.36',
}
#   'Referer': 'https://www.ciweimao.com/chapter/102036462',
#    'Cookie': 'ci_session=h05g9v8lvvt2hr5oacgdrqhi5fsd8s6a;'
#
response = requests.get('https://ciweimao.com/', headers=headers)
cookie = response.cookies['ci_session']
headers['Cookie'] = 'ci_session='+cookie
# 设置cookie
cookie = response.cookies['ci_session']

class CWMCrawlContent(object):

    @staticmethod
    def getContent(chapter_id):
        # Referer
        headers['Referer'] = 'https://www.ciweimao.com/chapter/' + chapter_id
        # 发送post获取chapter_access_key
        res = requests.post('https://www.ciweimao.com/chapter/ajax_get_session_code', headers=headers,
                            data={'chapter_id': int(chapter_id)})
        print(headers)
        chapter_access_key = json.loads(res.text)['chapter_access_key']
        # 设置data,请求
        data = {
            'chapter_id': int(chapter_id),
            'chapter_access_key': chapter_access_key
        }
        print(data)
        content_req = requests.post('https://www.ciweimao.com/chapter/get_book_chapter_detail_info',
                                    data=data, headers=headers)
        content_text = json.loads(content_req.text)
        print(content_text)
        canshu = {
            'accessKey': chapter_access_key,
            'keys': content_text['encryt_keys'],
            'content': content_text['chapter_content'],
        }

        canshu = json.dumps(canshu)
        with open('./ciweimao.js', 'r', encoding='UTF-8') as file:
            js = file.read()
        comp = execjs.compile(js)
        result = comp.call("decrypt", canshu)
        return result
